<template>
  <el-dialog
    :title="`${isCreate ? '发布' : '编辑'}消息`"
    :visible.sync="dialogVisible"
    class="dialog"
    width="800px">
    <el-form
      :model="formData"
      style="margin-right: 20px"
      label-width="60px"
      ref="form"
      :rules="rules"
      size="small">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="详情" prop="content">
        <rich-text
          style="min-height: 200px"
          :options="editorOption"
          v-model="formData.content">
        </rich-text>
      </el-form-item>
    </el-form>
    <dialog-footer
      slot="footer"
      @cancel="dialogVisible = false"
      @confirm="confirm"
    />
  </el-dialog>
</template>
<script>
import { saveMessage, updateMessage } from '@/api/base-config';

export default {
  props: {
    initFormData: Object,
    isCreate: Boolean,
  },
  data() {
    return {
      formData: {
        ...this.initFormData,
      },
      dialogVisible: false,
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
      },
      editorOption: {
        placeholder: '请输入消息详情',
      },
    };
  },
  watch: {
    initFormData(val) {
      this.formData = { ...val };
    },
  },
  methods: {
    async confirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const { title, content, id } = this.formData;
          if (content) {
            if (this.isCreate) {
              await saveMessage({ title, content });
            } else {
              await updateMessage({
                title, content, id,
              });
            }
            this.dialogVisible = false;
            this.$emit('confirm');
          } else {
            this.$message.error('消息内容不能为空');
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
  .dialog {
    ::v-deep .el-input__inner {
      width: 220px;
    }
  }
</style>
